package api

import (
	"flag"
	"github.com/gin-gonic/gin"
	"net/http"
	"project_api/intrenal/api/request"
	"project_api/intrenal/api/response"
	"project_api/intrenal/handler"
	"project_api/pkg"
	__ "project_user_srv/proto"
	"strconv"
)

var (
	userServer = flag.String("userServer", "127.0.0.1:50051", "The server address")
	client     = handler.NewClient().UserServerClient(userServer)
)

func Register(c *gin.Context) {
	var json request.UserRegister
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	register, err := client.Register(c, &__.RegisterRequest{
		Username: json.Username,
		Password: json.Password,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}

	response.Response(c, 200, "注册成功", register)

}

func Login(c *gin.Context) {
	var json request.UserRegister
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	register, err := client.Login(c, &__.LoginRequest{
		Username: json.Username,
		Password: json.Password,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}

	tokenHandler, _ := pkg.TokenHandler(strconv.FormatInt(register.Id, 10))

	response.Response(c, 200, "登录成功", tokenHandler)

}

func Home(c *gin.Context) {
	var json request.HomeList
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	value, _ := c.Get("userId")

	userId, _ := strconv.Atoi(value.(string))

	home, err := client.Home(c, &__.HomeRequest{
		Page:     int64(json.Page),
		PageSize: int64(json.PageSize),
		UserId:   int64(json.UserId),
		MyId:     int64(userId),
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}

	response.Response(c, 200, "主页展示成功", home)
}
